package com.qf.fmall.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;

import java.util.Date;

public class TokenUtils {

    public static final String PRIVATE_KEY = "qfsy2306";


    /**
     * 创建JWT
     * @param username    用户名
     * @param userid      用户id
     * @param expireTime  有效期 （单位秒钟）
     * @return token字符串
     */
    public static String createJWT(String username,Integer userid,Integer expireTime){

        // 使用 Hutool的 JWT工具创建
        String token = JWT.create()
                .setSubject(userid+"")
                .setPayload("name", username)
                .setPayload("sex", "女")
                .setIssuer("qfsy")
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * expireTime))
                .setKey(PRIVATE_KEY.getBytes())
                .sign();

        return token;
    }


    public static boolean checkJWT(String jwt){

        // 使用hutool提供的方法进行校验
        boolean verify = JWT.of(jwt)
                .setKey(PRIVATE_KEY.getBytes())
                .validate(0);
//                .verify();
        return verify;

    }


    public static void main(String[] args) throws InterruptedException {
//        String token = createJWT("luffy001", 1, 120);
//        System.out.println(token);

//        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwibmFtZSI6Imx1ZmZ5MDAxIiwic2V4Ijoi5aWzIiwiaXNzIjoicWZzeSIsImV4cCI6MTcxMzk0NzUwNX0.IVpQRkoIk8FXpY-O1-A17o2incTNaModek6r3nalY";

        String token = createJWT("luffy001", 1, 5);
        System.out.println(checkJWT(token));
        Thread.sleep(6000);
        System.out.println(checkJWT(token));

    }


    public static boolean checkToken(String token) {

        String[] split = token.split("---");
        String username = split[0];
        String sign = split[1];

        // 重算签名
        String signMd5 = SecureUtil.md5(PRIVATE_KEY + username);
        return sign.equals(signMd5);

    }
}
